/*
 * This file is part of LangMan.
 *
 * LangMan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * LangMan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LangMan.  If not, see <http://www.gnu.org/licenses/>.
 */

package langman.gui.tree;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeView;
import javafx.scene.layout.VBox;
import langman.gui.tree.buttons.ButtonControl;
import langman.gui.tree.sets.SetTabPane;
import langman.util.doping.Inject;
import langman.util.doping.SingletonBean;
import langman.util.guifactory.AbstractFXMLBeanControl;
import langman.util.guifactory.GUIFactory;

@SuppressWarnings("rawtypes")
@SingletonBean
public class TreeControl extends AbstractFXMLBeanControl {
    private final GUIFactory guiFactory;
    private final RootItem rootItem;
    private final TreeItemSelectionService treeItemSelectionService;

    @FXML
    private TreeView treeView;

    @FXML
    private TextField filterTextField;

    @FXML
    private Button filterButton;


    @Inject
    public TreeControl(GUIFactory guiFactory, RootItem rootItem, TreeItemSelectionService treeItemSelectionService) {
        this.guiFactory = guiFactory;
        this.rootItem = rootItem;
        this.treeItemSelectionService = treeItemSelectionService;
    }

    @Override
    public void initializeAfterInjection() {
        SetTabPane setTabPane = guiFactory.createControl(SetTabPane.class);
        ButtonControl buttonControl = guiFactory.createControl(ButtonControl.class);

        VBox node = getNode();
        node.getChildren().add(0, setTabPane.getNode());
        node.getChildren().add(buttonControl.getNode());

        treeView.setRoot(rootItem);
        rootItem.setExpanded(true);

        treeItemSelectionService.selectedItemProperty().bind(treeView.getSelectionModel().selectedItemProperty());

        treeView.setCellFactory(treeView -> new DecoratedTreeCell());

        treeView.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
            if (newValue instanceof SelectionAwareTreeItem) {
                ((SelectionAwareTreeItem) newValue).selected();
            }
        });

        filterButton.setOnAction(actionEvent -> {
            rootItem.filter(filterTextField.getText());
        });
    }
}
